<template>
  <div class="d-flex-c full-box">
    <div
      class="operation-panel p-h-s"
      v-show="expanded"
    >
      <div class="flex-between m-b-mini">
        <!-- <el-popover
          placement="bottom-end"
          width="200"
          trigger="hover"
        >
          标准历时点雨量已保存信息
          <span
            slot="reference"
            style="color: #424e61;"
            class="c-pointer"
          >已保存信息<i class="el-icon-caret-bottom el-icon--right" /></span>
        </el-popover> -->
        <el-tag
          v-if="targetPosition.length"
          closable
          @close="closeTag"
        >
          <span
            class="m-b-mini"
            v-if="!targetName"
          >目标坐标：{{ `Ⓔ ${$helper.formatDegree(targetPosition[0])} Ⓝ ${$helper.formatDegree(targetPosition[1])}` }}</span>
          <span v-else>{{ targetName }}</span>
        </el-tag>
        <div v-else />
        <el-button
          size="mini"
          type="primary"
          plain
          @click="openRecords"
        >
          已保存信息
        </el-button>
      </div>
      <el-form
        size="mini"
        :model="formData"
        :rules="rules"
        label-width="60px"
        ref="form"
      >
        <el-form-item
          label="雨量"
          prop="YL"
        >
          <BKInput
            v-model="formData.YL"
            size="mini"
            is-number
            :digits="2"
          >
            <template slot="append">
              mm
            </template>
          </BKInput>
        </el-form-item>
        <el-form-item
          label="历时"
          prop="LS"
        >
          <RadioButton
            v-model="formData.LS"
            dictionary-key="YSQJC_JC_BYTJBZLS"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="Ht"
              prop="HT"
            >
              <BKInput
                v-model="formData.HT"
                size="mini"
                is-number
                :digits="2"
              >
                <template slot="append">
                  mm
                </template>
              </BKInput>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="Cv"
              prop="CV"
            >
              <BKInput
                v-model="formData.CV"
                size="mini"
                is-number
                :digits="2"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="7">
            <el-dropdown
              split-button
              @click="startPick"
              size="mini"
              class="m-l-mini"
              @command="handleCommand"
            >
              地图点选
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="clearPoint">
                  清除点位
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col> -->
        </el-row>
      </el-form>
      <div class="buttons d-flex ai-c jc-c">
        <el-button
          size="mini"
          type="primary"
          @click="getParams"
          plain
        >
          获取计算参数
        </el-button>
        <el-button
          size="mini"
          type="primary"
          @click="calculate"
          :disabled="!targetPosition.length"
        >
          计算
        </el-button>
        <el-button
          size="mini"
          type="primary"
          @click="calculateAndSave"
          :disabled="!targetPosition.length"
        >
          计算并保存
        </el-button>
      </div>
    </div>
    <div class="p-h-mini">
      <el-divider>
        <div
          class="split-icon"
          @click="expanded = !expanded"
        >
          <i class="el-icon-arrow-down" />
          <i class="el-icon-arrow-up" />
        </div>
      </el-divider>
    </div>
    <div class="flex-1 overflow-hidden">
      <BKTable
        ref="grid"
        :has-add="false"
        :has-batch-remove="false"
        :toolbar-config="null"
        :has-pager="false"
        style="padding-top: 0;"
        :has-checkbox="false"
        :columns="columns"
        :data="tableData"
        class="p-a-mini"
        :row-class-name="rowClassName"
      >
        <template #toolbarLeft>
          <div
            class="full-box flex-between f-16"
            style="margin-bottom: 4px;"
          >
            <span v-show="cxq">重现期 <span
              style="color: #49c398;"
              class="f-w"
            >{{ cxq }}</span> 年</span>
            <span v-show="!cxq" />
            <el-button
              size="mini"
              type="primary"
              plain
              @click="exportData"
              :loading="exportLoading"
            >
              导出
            </el-button>
          </div>
        </template>
      </BKTable>
    </div>
    <SaveRecords
      ref="records"
      meta-set="YSQJC_BYTJ_BZLSCXQ"
      id-key="BZID"
      @change="clickSaveInfo"
    />
  </div>
</template>

<script>
import SaveRecords from '../save-records.vue'
import RadioButton from '../radio-button.vue'
export default {
  name: 'StandardTabPanel',
  components: { RadioButton, SaveRecords },
  data () {
    return {
      formData: {
        YL: '',
        LS: '3',
        HT: '',
        CV: ''
      },
      rules: {
        YL: [{ required: true, message: '请填写雨量' }],
        LS: [{ required: true, message: '请选择历时' }],
        HT: [{ required: true, message: '请填写Ht' }],
        CV: [{ required: true, message: '请填写Cv' }]
      },
      expanded: true,
      columns: [
        { title: '历时', field: 'LS_TEXT' },
        { title: '年一遇', field: 'NYY' },
        { title: '频率（%）', field: 'PL' },
        {
          field: 'HTP',
          slots: {
            header: () => {
              return [
                <div class="d-flex-c ai-c">
                  <span>Htp</span>
                  <span>{'(mm)'}</span>
                </div>
              ]
            }
          },
          formatter: ({ cellValue }) => cellValue.toFixed(1)
        }
      ],
      tableData: [],
      cxq: '',
      exportLoading: false,
      targetPosition: [],
      targetName: '',
      targetId: ''
    }
  },
  methods: {
    rowClassName ({ row }) {
      if (row.BH === '1') {
        return 'c-red'
      } else {
        return ''
      }
    },
    async calculate () {
      const v = await this.$refs.form.validate()
      // if (!this.position) {
      //   this.$message.warning('请在地图上选择点位')
      //   return
      // }
      const LS_TEXT = await this.$utils.dictionary.getOptionNameByValue('YSQJC_JC_BYTJBZLS', this.formData.LS)
      if (v) {
        const { cxq, gcdata } = await this.$request.post('/ysjc/bytjjs/getbzlsgc', {
          yl: this.formData.YL,
          ht: this.formData.HT,
          cv: this.formData.CV,
          ls: this.formData.LS
        })
        this.cxq = cxq
        this.tableData = gcdata.map(item => ({ ...item, LS_TEXT }))
      }
    },
    async calculateAndSave () {
      await this.calculate()
      this.$request.post('/ysjc/bytjjs/savebzlscg', {
        gnq: { ...this.formData, CXQ: this.cxq, JD: this.targetPosition[0], WD: this.targetPosition[1], STCD: this.targetId },
        gcb: this.tableData
      })
      this.$message.success('操作成功')
    },
    startPick () {
      this.clearPoint()
      this.formData.CV = ''
      this.formData.HT = ''
      if (!this.formData.LS) {
        this.$message.warning('请先选择历时')
        return
      }
      this.$mapManager.invoke('showTool')
      this.$mapManager.invoke('startDrawByOptions', { type: 'Point', eventKey: 'pick' })
    },
    async pick ({ result }) {
      this.getHtAndCvByPosition(result)
    },
    async renderLine (data, point, layer, type) {
      const list = []
      const values = []
      for (const item of data) {
        const point = item ? await this.$mapManager.invoke('transfromFeature', item.foot_point) : null
        list.push(point.getGeometry().getCoordinates())
        values.push(item.tzzl)
      }
      list.splice(1, 0, point.getGeometry().getCoordinates())
      const lineGeom = new window.ol.geom.LineString(list)
      const feature = new window.ol.Feature()
      feature.setGeometry(lineGeom)
      feature.setProperties({ type, values })
      feature.setStyle(this.getStyle)
      layer.getSource().addFeature(feature)
    },
    getStyle (feature) {
      const { type, values } = feature.getProperties()
      const styles = []
      styles.push(new window.ol.style.Style({
        stroke: new window.ol.style.Stroke({
          color: type === 'cv' ? '#7019ff' : '#e04545',
          width: 2,
          lineDash: [10, 10]
        }),
        image: new window.ol.style.Circle({
          radius: 4,
          fill: new window.ol.style.Fill({
            color: '#ffff'
          }),
          stroke: new window.ol.style.Stroke({
            color: type === 'cv' ? '#7019ff' : '#e04545',
            width: 2
          })
        })
      }))
      styles.push(
        new window.ol.style.Style({
          geometry: function (feature) {
            const coordinates = feature.getGeometry().getCoordinates()
            const points = [coordinates[0]]
            if (coordinates.length > 2) {
              points.push(coordinates[2])
            }
            return new window.ol.geom.MultiPoint(points)
          },
          image: new window.ol.style.Circle({
            radius: 4,
            fill: new window.ol.style.Fill({
              color: '#ffff'
            }),
            stroke: new window.ol.style.Stroke({
              color: type === 'cv' ? '#7019ff' : '#e04545',
              width: 2
            })
          })
        })
      )
      styles.push(
        new window.ol.style.Style({
          geometry: function (feature) {
            const coordinates = feature.getGeometry().getCoordinates()
            return new window.ol.geom.Point(coordinates[1])
          },
          image: new window.ol.style.Circle({
            radius: 6,
            fill: new window.ol.style.Fill({
              color: '#ffff'
            }),
            stroke: new window.ol.style.Stroke({
              color: '#00dc10',
              width: 2
            })
          })
        })
      )
      const firstCoordinates = feature.getGeometry().getFirstCoordinate()
      const list = [firstCoordinates]
      if (feature.getGeometry().getCoordinates().length > 2) {
        const lastCoordinates = feature.getGeometry().getLastCoordinate()
        list.push(lastCoordinates)
      }
      list.forEach((item, i) => {
        styles.push(new window.ol.style.Style({
          geometry: new window.ol.geom.Point(item),
          text: new window.ol.style.Text({
            font: 'bold 0.8rem sans-serif',
            text: values[i].toString(),
            fill: new window.ol.style.Fill({
              color: type === 'cv' ? '#7019ff' : '#e04545'
            }),
            offsetY: 20
          })
        }))
      })
      return styles
    },
    handleCommand (command) {
      this[command]()
    },
    clearPoint () {
      this.$mapManager.invoke('clearLayers')
      this.$mapManager.invoke('clearLayers', ['graphicLayer', 'showinglayer'])
      // this.position = null
    },
    async exportData () {
      this.exportLoading = true
      const { data, fileName } = await this.$request.getFileStreamByPost('ysjc/bytjjs/exportNew', {
        table_name: 'YSQJC_BYTJ_BZLSCXQJSGC',
        data: this.tableData.map((item, i) => ({
          XH: i + 1,
          HTP: item.HTP,
          LS: item.LS_TEXT,
          PL: item.PL,
          NYY: item.NYY,
          BH: item.BH
        }))
      })
      this.$request.downloadBlobFile(data, fileName)
      this.exportLoading = false
    },
    openRecords () {
      this.$refs.records.open()
    },
    async clickSaveInfo (row) {
      this.formData = row
      const { rows } = await this.$request.singleTableOperation({
        url: '/grid/getTableData',
        metaSet: 'YSQJC_BYTJ_BZLSCXQJSGC',
        methodCode: 'selectJsGc',
        methodParams: { BZID: row.BZID }
      })
      this.cxq = row.CXQ
      this.tableData = rows
      this.targetPosition = [row.JD, row.WD]
      this.setPosition({ coordinate: this.targetPosition, name: row.STCD ? `${row.STNM} ${row.STCD}` : '', id: row.STCD })
    },
    async getHtAndCvByPosition (param) {
      let feature = null
      let wkt = null
      if (Array.isArray(param)) {
        const point = this.$mapManager.getMapComponent().map1.bkol.getPoint(param[0], param[1])
        feature = new window.ol.Feature(point)
        wkt = await this.$mapManager.invoke('transfromFeature', feature, false)
      } else {
        wkt = param
        feature = await this.$mapManager.invoke('transfromFeature', param)
      }
      const { cvdata, htdata, ht, cv, msg } = await this.$request.post('/ysjc/bytjjs/getpitcvht', { point: wkt, ht: this.formData.LS })
      this.formData.CV = cv || ''
      this.formData.HT = ht || ''
      const layer = await this.$mapManager.invokeUtils('getLayer', 'graphicLayer')
      layer.getSource().clear()
      // this.position = feature.getGeometry().getCoordinates()
      cvdata && this.renderLine(cvdata, feature, layer, 'cv')
      htdata && this.renderLine(htdata, feature, layer, 'ht')
      if (msg) {
        this.$message.warning(msg)
      } else {
        this.$message.success('获取数据成功')
      }
    },
    async setPosition ({ coordinate, name, id }) {
      const layer = await this.$mapManager.invokeUtils('getLayer', 'graphicLayer')
      layer.getSource().clear()
      this.targetPosition = coordinate
      this.targetName = name || ''
      this.targetId = id || ''

      const feature = new window.ol.Feature(new window.ol.geom.Point(coordinate))
      feature.setStyle(new window.ol.style.Style({
        image: new window.ol.style.Circle({
          radius: 6,
          fill: new window.ol.style.Fill({
            color: '#ffff'
          }),
          stroke: new window.ol.style.Stroke({
            color: '#00dc10',
            width: 2
          })
        })
      }))
      layer.getSource().addFeature(feature)
    },
    getParams () {
      if (!this.targetPosition.length) {
        this.$message.warning('请在地图点选或者选择一个站点')
        return
      }
      if (!this.formData.LS) {
        this.$message.warning('请选择历时')
        return
      }
      this.$emit('changeStateInStandard', this.formData.LS)
      this.getHtAndCvByPosition(this.targetPosition)
    },
    closeTag () {
      this.targetPosition = []
      this.targetName = ''
      this.$mapManager.invoke('clearLayers', ['graphicLayer', 'modifylayer'])
    }
  },
  created () {
    this.$mapManager.addEventListener('mapModifyEnd-pick', this.setPosition)
    // this.$root.$on('getHtAndCvByPosition', this.getHtAndCvByPosition)
    this.$root.$on('mapPick', this.setPosition)
  },
  beforeDestroy () {
    this.$mapManager.removeEventListener('mapModifyEnd-pick', this.setPosition)
    // this.$root.$off('getHtAndCvByPosition', this.getHtAndCvByPosition)
    this.$root.$off('mapPick', this.setPosition)
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-input-group__append {
  padding: 0 10px;
}

.split-icon {
  position: relative;
  width: 20px;
  height: 22px;
  cursor: pointer;

  > i {
    position: absolute;

    &:first-child {
      top: 0;
      left: 50%;
      transform: translateX(-50%);
    }

    &:last-child {
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
    }
  }

  &:hover {
    > i {
      color: #063ab6;
      font-weight: bold;
    }
  }
}

::v-deep .el-divider__text {
  padding: 0 10px;
}

::v-deep .el-divider--horizontal {
  margin: 20px 0 10px;
}

::v-deep .el-dropdown__caret-button {
  height: 28px;
}
</style>
